import { Injectable } from '@angular/core';
import {BaseService, httpOptions} from '../../../core/service/base.service';
import {_HttpClient} from '@delon/theme';
import {Observable} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SysMenuService  extends BaseService{

  getUrl(): string {
    return "api/sys-menu";
  }

  constructor(http: _HttpClient) {
    super(http);
  }

  /** POST: add a new object to the server */
  save(object: any): Observable<any> {
    return this.http.post<any>(this.getUrl() + '/save', object, httpOptions).pipe(
      tap((obj: any) => this.log(`added object =${obj}`)),
      catchError(this.handleError<any>('addany')),
    );
  }

  menuTree(): Observable<any> {
    const url = `${this.getUrl()}/menu-tree`;
    return this.http.get<any>(url).pipe(
      tap((obj: any) => this.log(`menu-tree =${obj}`)),
      catchError(this.handleError<any>(`menu-tree`)),
    );
  }

  userMenuTree(): Observable<any> {
    const url = `${this.getUrl()}/get-user-menu-tree`;
    return this.http.get<any>(url).pipe(
      tap((obj: any) => this.log(`menu-tree =${obj}`)),
      catchError(this.handleError<any>(`menu-tree`)),
    );
  }
  /**
   * 方法作用的注释
   * 并转换成select数据结构
   * @param keyword 收发室名称
   */
  getRepositoryOfOptionData(keyword?: string): Observable<string[]> {
    const page = { page: 0, size: 100 };
    let queryParams = page;
    if (keyword) {
      queryParams = { ...page, ...{ repoName: keyword } };
    }
    return this.http
      .get(this.getUrl() + `/all`, queryParams)
      .pipe(
        map((resp: any) => {
          const arr = [];
          const list = resp.data;
          if (list && list.length) {
            list.forEach(element => {
              arr.push({ title: element.menuName, key: element.id });
            });
          }
          return arr;
        }),
      );
  }
}
